package com.yisu.expressway.onedollar.presenter.impl;

import android.content.Context;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.RecordHistoryItem;
import com.yisu.expressway.onedollar.model.SalesGoodObj;
import com.yisu.expressway.onedollar.model.WinningRecord;
import com.yisu.expressway.onedollar.presenter.IRecordHistoryPresenter;
import com.yisu.expressway.onedollar.view.IRecordHistoryView;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by shijunfeng on 2016/12/14.
 */
public class RecordHistoryPresenterImp implements IRecordHistoryPresenter {
    private Context mContext;
    private List<RecordHistoryItem> mRecordList;
    private IRecordHistoryView mView;

    public RecordHistoryPresenterImp(Context mContext, IRecordHistoryView mView) {
        this.mContext = mContext;
        this.mView = mView;
    }


    @Override
    public void init() {

    }

    @Override
    public void fetchMore(long barcode, int start, int pageSize) {
        if (pageSize <= 0) {
            return;
        }
        Map<String, Object> params = new HashMap();

        int pageIndex = getPageIndex(start, pageSize);

        params.put("pageindex", pageIndex);
        params.put("pagesize", pageSize);
        params.put("barcode", barcode);
        ApiClientHelper.postApi(ApiSetting.getWinningRecordHistoryList(), new TypeToken<List<RecordHistoryItem>>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<List<RecordHistoryItem>>>() {
            @Override
            public void onResponse(ApiResult<List<RecordHistoryItem>> result) {
                if (!result.success) {
                    mView.showToast(result.getMsg());
                    return;
                }
                mRecordList = result.getResult();
                mView.refreshView(true);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mView.showToast(volleyError.getMessage());
                mView.refreshView(false);
            }
        }, mContext);
    }

    @Override
    public List<RecordHistoryItem> getRecordList() {
        return mRecordList;
    }

    private int getPageIndex(int start, int pageSize) {
        int round = start / pageSize;

        return round + 1;
    }
}
